#!/bin/bash

# set -x

: ${HBASE_HOME:=/home/hbase}
: ${HBASE_CONF_DIR:=/home/hbase/conf}

# disable default zookeeper
sed -i 's/# export HBASE_MANAGES_ZK=true/export HBASE_MANAGES_ZK=false/' $HBASE_CONF_DIR/hbase-env.sh

. ${HBASE_CONF_DIR}/hbase-env.sh
. ${HBASE_HOME}/bin/hbase-config.sh
. ${HBASE_HOME}/bin/hbase-common.sh

# Directory to find config artifacts
CONFIG_DIR="/opt/hbase-config"

# set region server hostname
sed -i "s/HOSTNAME/$(hostname)/" ${CONFIG_DIR}/hbase-site.xml

# zookeeper
if [[ -n "$ZOOKEEPER_QUORUM" ]];then
    # value: zk-1,zk-2,zk-3
    sed -i "s#ZOOKEEPER_QUORUM#${ZOOKEEPER_QUORUM}#" ${CONFIG_DIR}/hbase-site.xml
else
    echo "[ERROR] ZOOKEEPER_QUORUM is null."
    exit 1
fi

# hdfs
if [[ -n "$HBASE_ROOTDIR" ]];then
    # value: hdfs://hadoop-hadoop-hdfs-nn:9000/hbase
    sed -i "s#HBASE_ROOTDIR#${HBASE_ROOTDIR}#" ${CONFIG_DIR}/hbase-site.xml
else
    echo "[ERROR] \$HBASE_ROOTDIR is null."
    exit 1
fi

# Copy config files from volume mount
for f in hbase-site.xml; do
    if [[ -e ${CONFIG_DIR}/$f ]]; then
        cp ${CONFIG_DIR}/$f $HBASE_CONF_DIR/$f
    else
        echo "[ERROR] Could not find $f in $CONFIG_DIR"
        exit 1
    fi
done

echo "[INFO] $(date +'%Y-%m-%d %H:%M%S') $HOSTNAME Wait $WAIT_HOSTS"
${CONFIG_DIR}/wait

# Init hbase table
if [[ "${INIT_TABLE}" == "true" ]]; then
    # (sleep 120; echo "[INFO] $(date +'%Y-%m-%d %H:%M%S') $HOSTNAME Init hbase table."; env COMPRESSION=SNAPPY HBASE_HOME=$HBASE_HOME ${CONFIG_DIR}/create_table.sh) &
    (sleep 120; echo "[INFO] $(date +'%Y-%m-%d %H:%M%S') $HOSTNAME Init hbase table."; env COMPRESSION=none HBASE_HOME=$HBASE_HOME ${CONFIG_DIR}/create_table.sh) &
fi

# Start service
command=$1
case $command in
    master)
        echo "[INFO] $(date +'%Y-%m-%d %H:%M%S') $HOSTNAME start master."
        exec gosu hadoop ${HBASE_HOME}/bin/hbase master start
        ;;
    regionserver)
        echo "[INFO] $(date +'%Y-%m-%d %H:%M%S') $HOSTNAME start regionserver."
        exec gosu hadoop ${HBASE_HOME}/bin/hbase regionserver start
        ;;
esac

exec "$@"
